package cc.verywell.pureblock.msg.nfs.idx;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cc.verywell.pureblock.func.node.KeyShell;
import cc.verywell.pureblock.msg.nfs.hd.LfsHdNeed;
import cc.verywell.pureblock.msg.nfs.idx.extraUpload.UploadSupply;
import cc.verywell.pureblock.util.BasicEntry;

/**
* 用于测试后续功能的纯内存实现
* Copyright © 2019 TanYaqiu. All rights reserved.
* @author TanYaqiu 
* @address flat 601
* @date 2019年10月2日 下午16:57:01
*/
public class NfsidxMainV0 implements NfsidxMain,LfsHdNeed {
	final private Map<KeyShell, NfsidxStructure> store = new ConcurrentHashMap<KeyShell, NfsidxStructure>();
	
	private UploadSupply uploadSupply;
	public NfsidxMainV0(UploadSupply uploadSupply) {
		this.uploadSupply = uploadSupply;
	}
	@Override
	public byte addIndex(KeyShell ks, NfsidxStructure idx) {
		if(idx!=store.compute(ks, (k,ov)->{
				if(ov==null)return idx;
				//内部文件，直接替换新的;if(!ov.isExternal())return ov;
				if(!idx.isExternal())return idx;
				return ov;
			})) {
				return ADD_EXISTS;
		}else {
			return ADD_OK;
		}
	}
	@Override
	public byte replaceIndex(KeyShell ks, NfsidxStructure oldidx, NfsidxStructure newidx) {
		if(newidx!=store.computeIfPresent(ks, (k,ov)->{
				if(ov==oldidx)return newidx;
				return ov;
			})) {
				return ADD_NOTSAME;
		}else {
			return ADD_OK;
		}	}
	@Override
	public byte removeIndex(KeyShell ks, NfsidxStructure idx) {
		if(store.remove(ks, idx)) {
			return REMOVE_OK;
		}else {
			return REMOVE_NOTSAME;
		}
	}
	@Override
	public NfsidxStructure getIndex(KeyShell ks) {
		return store.get(ks);
	}
	
	@Override
	public void fireHdTempFreeSpace(List<BasicEntry<KeyShell, NfsidxStructure>> idxes) {
		for (BasicEntry<KeyShell, NfsidxStructure> be : idxes) {
			NfsidxStructure newIdx = uploadSupply.needNewExternalFile(be.getKey(), be.getValue());
			if(newIdx==null)
				removeIndex(be.getKey(),be.getValue());
			else
				replaceIndex(be.getKey(),be.getValue(),newIdx);
		}
	}
	@Override
	public void fireHdTempStock(KeyShell key, NfsidxStructure idx) {
		addIndex(key, idx);
	}
	
}
